from django.shortcuts import render,HttpResponse
from .models import *
from rest_framework.views import APIView
from rest_framework.response import Response
from .sers import *
from qiniu import Auth,put_data,etag
from taobao.settings import AK,SK


def index(request):
    return render(request,'index.html')


def type_list(request):
    # 查询 所有的分类
    types = Category.objects.all()
    resp = render(request, "type_list.html", context={"types": types})
    return resp



def type_add(request):
    if request.method=="GET":
        # 获取到所有的分类 传给type_add.html
        type_list1 = Category.objects.filter(parent_id=None)
        resp = render(request,"type_add.html",context={"type_list1":type_list1})
        return resp
    elif request.method=="POST":
        name=request.POST.get("name")
        parent_id=request.POST.get("parent")
        # 保存数据
        Category.objects.create(name=name,parent_id=parent_id)
        resp=HttpResponse("添加分类成功")
        return resp


def goods_list(request):
    goodses=Goods.objects.all()
    return render(request,'goods_list.html',context={"goodses":goodses})


class GoodsAdd(APIView):
    def get(self, request):
        type_list1 = Category.objects.filter(parent_id=None)

        type_list2 = Category.objects.filter(parent_id=type_list1.first().id)

        tag_list = Tag.objects.filter(cate_id=type_list1.first().id)

        return render(request, "goods_add.html",
                      {"type_list1": type_list1, "type_list2": type_list2, "tag_list": tag_list})

    def post(self, request):
        name = request.POST.get("name")
        category = request.POST.get("category")
        tag = request.POST.get("tag")
        pic = request.FILES.get("pic")
        price = request.POST.get("price")
        store = request.POST.get("store")
        content = request.POST.get("content")
        baozhuang = request.POST.get("baozhuang")
        fuwu = request.POST.get("fuwu")

        pnames = request.POST.getlist("pname")
        pvalues = request.POST.getlist("pvalue")

        print(name, category, tag, price, store, content, baozhuang, fuwu)
        print(pnames, pvalues)
        pic1 = self.qiniu_upload(pic)
        if not pic1:
            pic1 = ""

        goods_obj = Goods.objects.create(name=name, category_id=category, tag_id=tag,pic=pic, pic1=pic1,price=price, store=store,
                                         content=content, baozhuang=baozhuang, fuwu=fuwu)

        # 保存商品属性  写事务

        for i in range(len(pnames)):
            if pnames[i]:
                Goods_Item.objects.create(name=pnames[i], value=pvalues[i], goods_id=goods_obj.id)

        return HttpResponse("添加成功")

    @staticmethod
    def qiniu_upload(pic):
        # 需要填写你的 Access Key 和 Secret Key
        access_key = AK
        secret_key = SK

        # 构建鉴权对象
        q = Auth(access_key, secret_key)

        # 要上传的空间
        bucket_name = '1909a'

        # 上传后保存的文件名
        key = None

        # 生成上传 Token，可以指定过期时间等
        token = q.upload_token(bucket_name, key, 3600)

        # 要上传远程 传递来的图片

        ret, info = put_data(token, key, pic.read())
        print(info)
        print(ret)
        if info.status_code == 200:
            return ret["key"]
        else:
            return None


def tag_list(request):
    tag_list = Tag.objects.all()
    return render(request,'tag_list.html',{"tag_list":tag_list})


class Tag_add(APIView):
    def get(self,request):
        type_list1=Category.objects.filter(parent_id=None)
        return render(request,"tag_add.html",{"type_list1":type_list1})

    def post(self,request):
        name = request.POST.get("name")
        cate = request.POST.get("cate")
        Tag.objects.create(name=name,cate_id=cate)
        return HttpResponse("添加成功")


class CateAndTagByOneCate(APIView):

    def get(self, request):
        cid = request.query_params.get("cid")

        cate_list2 = Category.objects.filter(parent_id=cid)

        tag_list = Tag.objects.filter(cate_id=cid)

        resp = {}
        resp["code"] = 200
        resp["cate_list2"] = CateSer(cate_list2, many=True).data
        resp["tag_list"] = TagSer(tag_list, many=True).data

        return Response(resp)